Page({
  data: {
    form: {
      name: '',
      idCard: '',
      phone: '',
      address: '',
      model: '',
      serialNo: '',
      purchaseDate: '',
      dealer: '',
      invoiceAmount: '',
      bankName: '',
      bankAccount: '',
      invoiceImage: '',
      contractImage: '',
      certificateImage: '',
      idCardImage: ''
    },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '服务事项加载中...',

  // 显示全局加载
  showGlobalLoading(text = '服务事项加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

    machineTypes: ['拖拉机', '联合收割机', '插秧机', '播种机', '植保机械', '烘干机', '其他'],
    machineTypeIndex: -1,

    subsidyCategories: ['中央农机购置补贴', '省级农机购置补贴', '市县配套补贴'],
    subsidyCatIndex: -1,

    agreed: false,
    canSubmit: false,
    errors: {},
    showErrors: false
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('服务事项加载中...')
    console.log('农机购置补贴页面加载', options)
    
    // 页面加载完成，隐藏加载状态
    setTimeout(() => {
      this.hideGlobalLoading()
    }, 500)
  },

  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    this.setData({ [`form.${field}`]: value }, () => this.validateForm())
  },

  onMachineTypeChange(e) {
    const value = Number(e.detail.value)
    const machineType = this.data.machineTypes[value]
    this.setData({ machineTypeIndex: value, 'form.machineType': machineType }, () => this.validateForm())
  },

  onSubsidyCatChange(e) {
    const value = Number(e.detail.value)
    const subsidyCategory = this.data.subsidyCategories[value]
    this.setData({ subsidyCatIndex: value, 'form.subsidyCategory': subsidyCategory }, () => this.validateForm())
  },

  onDateChange(e) {
    const { value } = e.detail
    this.setData({ 'form.purchaseDate': value }, () => this.validateForm())
  },

  onUpload(e) {
    const { field } = e.currentTarget.dataset
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        setTimeout(() => {
          this.setData({ [`form.${field}`]: tempFilePath }, () => this.validateForm())
          wx.showToast({ title: '上传成功', icon: 'success' })
        }, 800)
      },
      fail: () => wx.showToast({ title: '图片选择失败', icon: 'none' })
    })
  },

  onDeclarationChange(e) {
    const agreed = e.detail.value.includes('agree')
    this.setData({ agreed }, () => this.validateForm())
  },

  validateForm() {
    const { form, agreed, showErrors } = this.data

    const requiredFields = ['name', 'idCard', 'phone', 'address', 'model', 'serialNo', 'purchaseDate', 'dealer', 'invoiceAmount', 'bankName', 'bankAccount', 'machineType', 'subsidyCategory']
    const hasAllFields = requiredFields.every((f) => form[f] && String(form[f]).trim())

    const requiredImages = ['invoiceImage', 'contractImage', 'certificateImage', 'idCardImage']
    const hasAllImages = requiredImages.every((f) => !!form[f])

    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    const phoneRegex = /^1[3-9]\d{9}$/
    const isIdCardValid = idCardRegex.test(form.idCard)
    const isPhoneValid = phoneRegex.test(form.phone)

    const amount = Number(form.invoiceAmount)
    const isAmountValid = !Number.isNaN(amount) && amount > 0

    const canSubmit = hasAllFields && hasAllImages && isIdCardValid && isPhoneValid && isAmountValid && agreed

    const errors = {}
    if (showErrors) {
      const names = {
        name: '姓名', idCard: '身份证号', phone: '联系电话', address: '家庭住址',
        model: '品牌型号', serialNo: '出厂编号/机身号', purchaseDate: '购机日期', dealer: '经销商/销售单位',
        invoiceAmount: '发票金额', bankName: '开户银行', bankAccount: '银行卡号', machineType: '农机类型', subsidyCategory: '补贴类别'
      }
      requiredFields.forEach((k) => { if (!form[k] || !String(form[k]).trim()) errors[k] = `请填写${names[k]}` })
      if (form.idCard && !isIdCardValid) errors.idCard = '身份证号格式不正确'
      if (form.phone && !isPhoneValid) errors.phone = '手机号格式不正确'
      if (!isAmountValid) errors.invoiceAmount = '请输入有效的发票金额'
      if (!form.invoiceImage) errors.invoiceImage = '请上传购机发票'
      if (!form.contractImage) errors.contractImage = '请上传购机合同'
      if (!form.certificateImage) errors.certificateImage = '请上传产品合格证'
      if (!form.idCardImage) errors.idCardImage = '请上传身份证照片'
      if (!agreed) errors.agreed = '请勾选申请声明'
    }

    this.setData({ canSubmit, errors })
  },

  onSubmit() {
    this.setData({ showErrors: true }, () => {
      this.validateForm()
      if (!this.data.canSubmit) {
        wx.showToast({ title: '请完善申请信息', icon: 'none' })
        return
      }
      setTimeout(() => {
        wx.showModal({
          title: '提交成功',
          content: '您的农机购置补贴申请已提交，预计10-15个工作日完成审核。',
          showCancel: false,
          confirmText: '确定',
          success: () => wx.navigateBack({ delta: 1 })
        })
      }, 1500)
    })
  },

  onShareAppMessage() {
    return { title: '农机购置补贴申请', path: '/pages/service/agriculture-rural/machinery-subsidy/index' }
  }
})


